package com.ybw.config;

import com.alibaba.fastjson2.JSON;
import com.ybw.service.impl.BananaProductServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 替换bean
 *
 * @author ybw
 * @version V1.0
 * @className MyBeanDefinitionRegistryPostProcessor
 * @date 2022/6/16
 **/
@Component
@Slf4j
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        // 注册Bean定义，容器根据定义返回bean
        log.info("所有bean:{}", JSON.toJSONString(beanDefinitionRegistry.getBeanDefinitionNames()));
        //要被替换的bean
        String beanName = "productService";
        if (beanDefinitionRegistry.containsBeanDefinition(beanName)) {
            // 先移除原来的bean定义
            beanDefinitionRegistry.removeBeanDefinition(beanName);

            // 注册我们自己的bean定义
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(BananaProductServiceImpl.class);
//        // 如果有构造函数参数, 有几个构造函数的参数就设置几个  没有就不用设置
//        beanDefinitionBuilder.addConstructorArgValue("构造参数1");
//        beanDefinitionBuilder.addConstructorArgValue("构造参数2");
//        beanDefinitionBuilder.addConstructorArgValue("构造参数3");
//        // 设置 init方法 没有就不用设置
//        beanDefinitionBuilder.setInitMethodName("init");
//        // 设置 destory方法 没有就不用设置
//        beanDefinitionBuilder.setDestroyMethodName("destory");
            // 将Bean 的定义注册到Spring环境
            beanDefinitionRegistry.registerBeanDefinition("myTestRegistryConfig", beanDefinitionBuilder.getBeanDefinition());
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        // bean的名字为key, bean的实例为value
//        Map<String, Object> beanMap = configurableListableBeanFactory.getBeansWithAnnotation(RestController.class);
//        log.info("所有 RestController 的bean {}", beanMap);
    }
}

